package service

import (
	"fmt"
	"path/filepath"
	"review-service/internal/data"
	"review-service/internal/utils"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/transport/http"
)

type ImageService struct {
	rep *data.ImageRepo
	log *log.Helper
}

func NewImageService(rep *data.ImageRepo, logger log.Logger) *ImageService {
	return &ImageService{
		rep: rep,
		log: log.NewHelper(logger),
	}
}

func (s *ImageService) UploadFile(ctx http.Context) error {
	req := ctx.Request()
	fileName := req.FormValue("name")
	file, handler, err := req.FormFile("file")
	s.log.Infof("UploadFile fileName: %s", fileName)
	if err != nil {
		s.log.Errorf("UploadFile fileName: %s, err: %v", fileName, err)
		return err
	}
	defer file.Close()
	newName := fmt.Sprintf("%s%s", utils.GetRandName(), filepath.Ext(handler.Filename))
	if err := s.rep.UploadImage(ctx, file, handler.Size, newName); err != nil {
		s.log.Errorf("UploadFile fileName: %s, err: %v", fileName, err)
		return err
	}
	s.log.Infof("save fileName to minio successful: %s, newName: %s", fileName, newName)
	return ctx.String(200, "File "+newName+" Uploaded successfully")
}
